package com.logos.cartoon.utils;

import com.logos.cartoon.entity.AuthUser;
import com.logos.cartoon.mapper.AuthUserMapper;
import com.logos.cartoon.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginUtil {

    @Resource
    private AuthUserMapper authUserMapper;

    @Resource
    private RedisUtil redisUtil;

    public static final String LOGIN_KEY_PHONE = "user:login:";

    public String getId() {
        if(redisUtil.exist(LOGIN_KEY_PHONE+LoginContextHolder.getLoginPhone())){
            log.info("user:login:phone cache hit");
            return redisUtil.get(LOGIN_KEY_PHONE+LoginContextHolder.getLoginPhone());
        }
        AuthUser authUser = new AuthUser();
        authUser.setPhone(LoginContextHolder.getLoginPhone());
        authUser = authUserMapper.queryByCondition(authUser);
        redisUtil.setNx(LOGIN_KEY_PHONE+LoginContextHolder.getLoginPhone(),String.valueOf(authUser.getId()),2L, TimeUnit.MINUTES);
        return String.valueOf(authUser.getId());
    }
}
